package com.dlc.shop.platform.task;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.dlc.shop.bean.enums.ShopStatus;
import com.dlc.shop.bean.model.Product;
import com.dlc.shop.bean.model.ShopDetail;
import com.dlc.shop.service.ProdExtensionService;
import com.dlc.shop.service.ProductService;
import com.dlc.shop.service.ShopDetailService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 统计店铺商品销量
 * @title: ShopSoldNumTask
 * @Author Chiley
 * @Date: 2023/3/21 15:19
 */

@Slf4j
@Component
@AllArgsConstructor
public class ShopSoldNumTask {

    private ShopDetailService shopDetailService;
    private ProductService productService;
    private ProdExtensionService prodExtensionService;


    /**
     * 统计店铺销量数据
     */
    @XxlJob("calculateShopSoldNum")
    public void calculateShopSoldNum() {
        List<ShopDetail> shopDetailList = shopDetailService.list(Wrappers.lambdaQuery(ShopDetail.class).eq(ShopDetail::getShopStatus, ShopStatus.OPEN.value()));
        Map<Long, ShopDetail> shopDetailMap = shopDetailList.stream().collect(Collectors.toMap(ShopDetail::getShopId, shopDetail -> shopDetail));
        List<Product> productList = productService.list();
        Map<Long, List<Product>> shopProductMap = productList.stream().collect(Collectors.groupingBy(Product::getShopId));
        shopProductMap.forEach((shopId, shopProductList) -> {
            ShopDetail shopDetail = shopDetailMap.get(shopId);
            if (Objects.isNull(shopDetail)) {
                return;
            }
            List<Long> prodIdList = shopProductList.stream().map(Product::getProdId).toList();
            if (CollUtil.isNotEmpty(prodIdList)) {
                Long shopSoldNum = prodExtensionService.getSoldNumByProdIds(prodIdList);
                shopDetail.setShopSoldNum(shopSoldNum);
            }
        });
        shopDetailService.updateBatchById(shopDetailList);
    }
}
